using System;
using System.Collections.Generic;
using K9Nano.Domain;
using K9Nano.EFCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;

namespace EFCoreTest
{
    public class TestDbContext : K9DbContext
    {
        public DbSet<Blog> Blogs { get; set; }

        public DbSet<Post> Posts { get; set; }

        public TestDbContext(DbContextOptions<TestDbContext> options) : base(options, null)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Blog>()
                .Property(x => x.CreationTime).HasDefaultValue(DateTimeOffset.UtcNow);

            base.OnModelCreating(modelBuilder);
        }

        //public override int SaveChanges(bool acceptAllChangesOnSuccess)
        //{
        //    var entries = ChangeTracker.Entries();
        //    foreach (var entry in entries)
        //    {
        //        if (entry.Entity is ISoftDelete softDelete)
        //        {
        //            var now = DateTime.UtcNow;
        //            if (entry.State == EntityState.Deleted)
        //            {
        //                entry.CurrentValues[nameof(ISoftDelete.IsDeleted)] = true;
        //                entry.State = EntityState.Modified;
        //            }
        //        }
        //    }

        //    return base.SaveChanges(acceptAllChangesOnSuccess);
        //}
    }

    public class Blog : Entity, ISoftDelete, IMustHaveTenant
    {
        public string Name { get; set; }
        public bool IsDeleted { get; set; }
        public virtual ICollection<Post> Posts { get; set; }
        public int TenantId { get; set; }

        public long? CreatorUserId { get; set; }
        public DateTimeOffset CreationTime { get; set; }

        public override string ToString()
        {
            return $"{Id},{Name}";
        }
    }

    public class Post : Entity, ISoftDelete, IMustHaveTenant
    {
        public string Name { get; set; }

        public long BlogId { get; set; }

        public bool IsDeleted { get; set; }

        public virtual Blog Blog { get; set; }
        public int TenantId { get; set; }
    }

}